package service

import (
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"shrimp-blog-server/app/dao"
	"shrimp-blog-server/app/model"
)

func (*CommentService) AddComment(req *ghttp.Request, comments ...model.Comment) {
	if len(comments) == 0 {
		responses.ErrorResponseExit(req, "评论内容不能为空")
	}

	affected, err := dao.Comment.Insert(comments...)
	if err != nil {
		g.Log("添加评论").Errorf("失败: %v", err)
		panic(gerror.Wrap(err, "添加评论失败"))
	}
	if affected == 0 {
		responses.ErrorResponseExit(req, "添加评论失败")
	}
	responses.SuccessResponse(req)
}

func (*CommentService) DeleteComment(req *ghttp.Request, id ...uint) {
	if len(id) == 0 {
		g.Log("删除评论").Errorf("失败: %v", "评论内容不能为空")
		responses.ErrorResponseExit(req, "评论内容不能为空")
	}
	comments := make([]model.Comment, len(id))

	for i := range comments {
		comments[i].Id = id[i]
		comments[i].Status = model.NotShowStatus
	}
	affected, err := dao.Comment.Delete(comments...)
	if err != nil {
		g.Log("删除评论").Errorf("失败: %v", err)
		panic(gerror.Wrap(err, "删除评论失败"))
	}
	if affected == 0 {
		responses.ErrorResponseExit(req, "删除评论失败")
	}
	responses.SuccessResponse(req)
}

func (*CommentService) UpdateComment(req *ghttp.Request, comments ...model.Comment) {
	if len(comments) == 0 {
		g.Log("更新评论").Errorf("失败: %v", "评论内容不能为空")
		responses.ErrorResponseExit(req, "评论内容不能为空")
	}
	affected, err := dao.Comment.Update(comments...)
	if err != nil {
		g.Log("更新评论").Errorf("失败: %v", err)
		panic(gerror.Wrap(err, "更新评论失败"))
	}
	if affected == 0 {
		responses.ErrorResponseExit(req, "更新评论失败")
	}
	responses.SuccessResponse(req)
}

func (*CommentService) GetComment(req *ghttp.Request, id ...uint) {
	if len(id) == 0 {
		g.Log("获取评论").Errorf("失败: %v", "评论ID不能为空")
		responses.ErrorResponseExit(req, "评论ID不能为空")
	}
	comment, err := dao.Comment.GetModelById(id...)
	if err != nil {
		g.Log("获取评论").Errorf("失败: %v", err)
		panic(gerror.Wrap(err, "获取评论失败"))
	}
	responses.Json(req, successCode, successMessage, comment)
}
func (*CommentService) GetCommentPage(req *ghttp.Request, page model.Page) {
	result, err := dao.Comment.GetModelsByPage(page.Page, page.Size)
	if err != nil {
		panic(gerror.Wrap(err, "获取评论列表失败"))
	}
	if result != nil {
		responses.ErrorResponseExit(req, "评论列表为空")
	}
	commentResponsePage := result[0].ConvertPage(result, page)
	commentResponsePage.Page.Total, err = dao.Comment.DB().Model(dao.Comment.Table).Count()
	if err != nil {
		panic(gerror.Wrap(err, "获取评论总数失败"))
	}
	responses.Json(req, successCode, successMessage, commentResponsePage)
}
